package com.broadengate.view.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.broadengate.bean.ContractInfo;
import com.broadengate.bean.DepartmentInfo;
import com.broadengate.bean.ProjectInfo;
import com.broadengate.bean.SessionInfo;
import com.broadengate.service.IncomeService;
import com.broadengate.util.JSONResult;
import com.broadengate.util.StringUtil;
import com.broadengate.view.pageModel.DataGrid;
import com.broadengate.view.pageModel.IncomeDetail;

/**
 * 收入管理
 * 
 * @author 木子传
 *
 */
@Controller
@RequestMapping("/IncomeController")
public class IncomeController
{
    private final static Logger log = Logger.getLogger(IncomeController.class);
    
    @Autowired
    private IncomeService incomeService;
    
    private List<DepartmentInfo> departmentInfoList;
    
    private String logUserName;
    
    /**
     * 获取完整部门结构树
     * 此方法用于返回一个满足TreeGriad的JSON对象
     * @return [参数说明]
     * 
     * @return List<OragnizationInfo> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/getIncomeTreeGird")
    @ResponseBody
    public List<IncomeDetail> getIncomeTreeGird(HttpServletRequest request, HttpServletResponse response)
    {
        //获取用户信息姓名
        SessionInfo session = (SessionInfo) request.getSession().getAttribute("session");
        logUserName = session.getEmployeeName();
        departmentInfoList = session.getDepartmentTree();
        //获取部门树
        DepartmentInfo dInfo = departmentInfoList.get(0);
        
        //获取当前系统的年份
        String year = StringUtil.getYearString(new Date());
        //获取前一年的年份
        String earlyYear = StringUtil.getYearString(new Date(), 1);
        String earlyTwoYear = StringUtil.getYearString(new Date(), 2);
        
        String[] yearList = { year, earlyYear, earlyTwoYear };
        
        List<IncomeDetail> resultList = new ArrayList<IncomeDetail>();
        
        this.creatIncomeTree(yearList, resultList, dInfo, logUserName);
        
        //遍历收入树，获取每年的最小的部门列表
        for (IncomeDetail incomeDetail : resultList)
        {
            //获取收入树的最后一个枝桠，也就是最小部门，最小部门下应该放入对应的收入信息
            List<IncomeDetail> lowestBranchList = new ArrayList<IncomeDetail>();
            incomeDetail.getLowestBranchList(lowestBranchList, incomeDetail);
            //遍历这些最小部门，获取这些最小部门下的所有收支列表
            for (IncomeDetail incomeDetail2 : lowestBranchList)
            {
                
                List<String> incomeNameList = incomeService.getIncomeByYearAndDepartmentId(incomeDetail2.getIncomeYear(),
                        incomeDetail2.getDepartmentId());
                
                if (incomeNameList != null && incomeNameList.size() > 0)
                {
                    
                    List<IncomeDetail> IncomeList = new ArrayList<IncomeDetail>();
                    //根据收支表名称（收支表名称为唯一的不重复的），获取此收支表对应的收入总计和合同、回款总计
                    for (String incomeName : incomeNameList)
                    {
                        //创建叶子对象，补充完数据后放入到最小部门下
                        IncomeDetail leaf = new IncomeDetail();
                        leaf.setPid(incomeName);
                        leaf.setIncomeYear(incomeDetail.getIncomeYear());
                        leaf.setDepartmentId(incomeDetail2.getDepartmentId());
                        leaf.setDepartmentName(incomeDetail2.getDepartmentName());
                        leaf.setIncomeName(incomeName);
                        //获取收支表的收入合计
                        leaf.setIncomeValue(incomeService.getIncomeValueByName(incomeName));
                        //设置收支表的合同信息
                        this.setContractInformation(leaf);
                        IncomeList.add(leaf);
                    }
                    this.setLowestBranchChildren(IncomeList, incomeDetail, incomeDetail2.getDepartmentId());
                }
            }
            
        }
        
        return resultList;
    }
    
    /**
     * 构建页面返回的treegrid对象
     * 根据年份生成对应的对象，暂支持当年和前2年的数据
     * @param yearList
     * @param resultList
     * @param dInfo [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void creatIncomeTree(String[] yearList, List<IncomeDetail> resultList, DepartmentInfo dInfo,
            String logUserName)
    {
        for (String year : yearList)
        {
            //根据部门树，构建收入树
            IncomeDetail tree = new IncomeDetail();
            tree.setPid(year);
            tree.setIncomeYear(year);
            tree.setLowestBranch("false");
            List<IncomeDetail> tmp = new ArrayList<IncomeDetail>();
            
            IncomeDetail oneLevel = new IncomeDetail();
            oneLevel.setPid(dInfo.getDepartmentName() + "-" + year);
            oneLevel.setIncomeYear(year);
            oneLevel.setDepartmentName(dInfo.getDepartmentName());
            oneLevel.setDepartmentId(dInfo.getDepartmentId());
            oneLevel.setOwners(dInfo.getHead());
            
            //判断是否有子阶段，如果有，则遍历子部门 并设置对应的isleaf字段
            if ("0".equals(dInfo.getHaschild()))
            {
                oneLevel.setLowestBranch("false");
                this.setLower(year, dInfo, oneLevel, logUserName);
            }
            tmp.add(oneLevel);
            tree.setChildren(tmp);
            
            //进行数据统计分析
            
            resultList.add(tree);
        }
        
    }
    
    /**
     * 递归查询所有自节点
     * @param year
     * @param dInfo
     * @param target [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    
    private void setLower(String year, DepartmentInfo dInfo, IncomeDetail target, String logUserName)
    {
        
        List<DepartmentInfo> list = dInfo.getChildren();
        List<IncomeDetail> idList = new ArrayList<IncomeDetail>();
        for (DepartmentInfo departmentInfo : list)
        {
            IncomeDetail idTemp = new IncomeDetail();
            idTemp.setPid(departmentInfo.getDepartmentName() + "-" + year);
            idTemp.setIncomeYear(year);
            idTemp.setDepartmentName(departmentInfo.getDepartmentName());
            idTemp.setDepartmentId(departmentInfo.getDepartmentId());
            idTemp.setOwners(departmentInfo.getHead());
            
            if ("0".equals(departmentInfo.getHaschild()))
            {
                idTemp.setLowestBranch("false");
            }
            
            if ("admin".equals(logUserName) || departmentInfo.getHead().indexOf(logUserName) > 0)
            {
                idList.add(idTemp);
            }
        }
        target.setChildren(idList);
        
        for (IncomeDetail idTemp : idList)
        {
            setLower(year, dInfo.getDepartmentInfoById(dInfo, idTemp.getDepartmentId()), idTemp, logUserName);
            
        }
        
    }
    
    /**
     * 查询合同金额和回款金额并放入到对象中
     * @param detail [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void setContractInformation(IncomeDetail detail)
    {
        //根据收支表名称查询所有此收支表对应的所有合同信息列表
        List<ContractInfo> contractList = incomeService.getContractInfoListByIncomeName(detail.getIncomeName());
        if (contractList != null && contractList.size() > 0)
        {
            //遍历合同列表，计算出对应的合同总额，回款总额，开票金额
            float contractValue = 0;
            float billValue = 0;
            for (ContractInfo contractInfo : contractList)
            {
                contractValue = contractValue + contractInfo.getContractMoney();
                billValue = billValue + contractInfo.getBillSumMoney();
            }
            
            detail.setBillValue(billValue);
            detail.setContractValue(contractValue);
        }
    }
    
    /**
     * 将收支表信息根据部门ID放入到对应的最小部门中
     * @param list
     * @param incomeDetail [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void setLowestBranchChildren(List<IncomeDetail> list, IncomeDetail incomeDetail, int departmentId)
    {
        if ("true".equals(incomeDetail.getLowestBranch()) && departmentId == incomeDetail.getDepartmentId())
        {
            incomeDetail.setChildren(list);
        }
        else
        {
            List<IncomeDetail> tmp = incomeDetail.getChildren();
            if (tmp != null && tmp.size() > 0)
            {
                for (IncomeDetail incomeDetail2 : tmp)
                {
                    this.setLowestBranchChildren(list, incomeDetail2, departmentId);
                }
            }
        }
    }
    
    /**
     * 查询收支的详细信息
     * <功能详细描述>
     * @param request
     * @param response
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/incomeDetail")
    public String incomeDetail(HttpServletRequest request, HttpServletResponse response)
    {
        String incomeName = request.getParameter("incomeName");
        //根据收入名称获取此收入的详细信息
        ProjectInfo info = incomeService.getIncomeDetail(incomeName);
        request.setAttribute("projectInfo", info);
        return "income/incomeDetail";
    }
    
    /**
     * 获取收入对应的合同信息
     * @return [参数说明]
     * 
     * @return DataGrid [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/getIncomeContract")
    @ResponseBody
    public DataGrid getIncomeContract(@RequestParam(value = "incomeName") String incomeName)
    {
        List<ContractInfo> contractInfoList = incomeService.getContractInfoListByIncomeName(incomeName);
        
        DataGrid result = new DataGrid();
        
        //遍历列表，计算相关的数据
        
        float contractMoneyTotal = 0;
        float billSumMoneyTotal = 0;
        float kpMoneyTotal = 0;
        if (contractInfoList != null && contractInfoList.size() > 0)
        {
            for (ContractInfo contractInfo : contractInfoList)
            {
                contractMoneyTotal = contractMoneyTotal + contractInfo.getContractMoney();
                billSumMoneyTotal = billSumMoneyTotal + contractInfo.getBillSumMoney();
                kpMoneyTotal = kpMoneyTotal + contractInfo.getKpMoney();
            }
            
            ContractInfo obj = new ContractInfo();
            obj.setContractName("合计");
            obj.setContractMoney(contractMoneyTotal);
            obj.setBillSumMoney(billSumMoneyTotal);
            obj.setKpMoney(kpMoneyTotal);
            
            result.setTotal(contractInfoList.size());
            result.setRows(contractInfoList);
            result.setObj(obj);
        }
        
        return result;
    }
    
    
    /**
     * 取消合同收入关联关系
     * @return [参数说明]
     * 
     * @return DataGrid [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/unRelateContracts")
    @ResponseBody
    public JSONResult unRelateContracts(HttpServletRequest request, HttpServletResponse response)
    {
        String contractids =request.getParameter("contractids");
        String incomeName = request.getParameter("incomeName");
        
       
        
        JSONResult result = new JSONResult();
        result.setSuccess(true);
        if(contractids==null||"".equals(contractids))
        {
            result.setSuccess(false);
            result.setMsg("请选择合同编号!");
            return result;
        }
        String[] contractIdArray = contractids.split(",");
        
        StringBuffer resultMsg = new StringBuffer();
        for (String contractId : contractIdArray)
        {
            try
            {
                incomeService.unRelateContracts(contractId, incomeName);
                resultMsg.append(contractId).append("取消成功<br>");
            }
            catch (Exception e)
            {
                resultMsg.append(contractId).append("取消失败<br>");
            }
        }
        result.setMsg(resultMsg.toString());
        return result;
    }
    
    /**
     * 进入预关联合同页面
     * @param request
     * @param response
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/preReleatContract")
    public String preReleatContract(HttpServletRequest request, HttpServletResponse response) 
    {
        
        String incomeName = request.getParameter("incomeName");
        request.setAttribute("incomeName", incomeName);
        return "income/preReleat";
    }
    
    @RequestMapping("/releatContract")
    @ResponseBody
    public JSONResult releatContract(HttpServletRequest request, HttpServletResponse response)
    {
        JSONResult result = new JSONResult();
        result.setSuccess(true);
        
        String contractids =request.getParameter("contractids");
        String incomeName = request.getParameter("incomeName");
        
        if(contractids==null||"".equals(contractids))
        {
            result.setSuccess(false);
            result.setMsg("未选择合同,关联失败!");
            return result;
        }
        String[] contractIdArray = contractids.split(",");
        
        
        StringBuffer resultMsg = new StringBuffer();
        for (String contractId : contractIdArray)
        {
            try
            {
                incomeService.releateContrats(contractId, incomeName);
                resultMsg.append(contractId).append("关联成功<br>");
            }
            catch (Exception e)
            {
                resultMsg.append(contractId).append("关联失败<br>");
                e.printStackTrace();
            }
        }
        
        result.setMsg(resultMsg.toString());
        return result;
    }
}
